#include "MSettings.h"

#include <QDebug>
#include <QDir>
#include <QMetaEnum>

static bool output = true;

static QMap<MSettings::INI, const char*> _pathMap{
    {MSettings::S_DEFAULT, "default.ini"},
    // {MSettings::RELEASE, ":/release"}
};

inline static QString realpath(const QString& name) {
    return QDir::homePath() + "/.config" +
           (name.indexOf('/') == 0 ? name : "/" + name);
}

static QMap<MSettings::INI, QSettings*> _map;

MSettings::MSettings(QObject* parent) : QObject(parent) {
    // Q_INIT_RESOURCE(MSettings);
    QMetaEnum metaEnum = QMetaEnum::fromType<MSettings::INI>();

    for (int i = 0; i < metaEnum.keyCount(); ++i) {
        auto ini = (MSettings::INI)metaEnum.value(i);

        if (_map.find(ini) != _map.end()) continue;

        if (ini == S_DEFAULT) {
            _map.insert(ini, new QSettings(QSettings::NativeFormat,
                                           QSettings::UserScope, "arashrun"));
            continue;
        }

        auto path = _pathMap.value(ini, "default.ini");
        QString rpath;
        if (path[0] == ':') {
            rpath = path;
        } else {
            rpath = realpath(path);
        }

        auto s = new QSettings(rpath, QSettings::IniFormat);
        // s->setIniCodec("UTF-8");

        _map.insert(ini, s);

        if (output) {
            qDebug() << ini << "reading" << rpath;
        }
    }
}

void MSettings::setNoOutput() { output = false; }

QSettings* MSettings::sets(INI ini) {
    static int _init = 0;

    if (_init == 0) {
        MSettings m;
        _init = 1;
    }

    return _map.value(ini);
}
